//
//  HDFillInfoView.m
//  HDecoration
//
//  Created by 曹群 on 15/8/15.
//  Copyright (c) 2015年 HDecoration. All rights reserved.
//

#import "HDFillInfoView.h"
@interface HDFillInfoView ()
@property CGPoint activePoint;
@property(nonatomic,strong)UIImageView *backgroundImage;
@property(nonatomic,strong)UIView *inputView;
@property(nonatomic,strong)UIButton *photoBtn;
@property(nonatomic,strong)UILabel *tipLabel;
@property(nonatomic,strong)HDTextField *nameField;
@property(nonatomic,strong)HDTextField *identityCardField;
@property(nonatomic,strong)HDTextField *driveCardField;
@property(nonatomic,strong)HDTextField *coachCardField;
@property(nonatomic,strong)UILabel *applyTypeLabel;
@property(nonatomic,strong)GXButton *coachBtn;
@property(nonatomic,strong)GXButton *companyBtn;
@property(nonatomic,strong)UIButton *nextStepBtn;
@property(nonatomic,strong)UIButton *uploadDriveCardBtn;
@property(nonatomic,strong)UIButton *uploadCoachCardBtn;
@property(nonatomic,strong)UIButton *clickedPhotoBtn;
@end

@implementation HDFillInfoView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self addSubview:self.backgroundImage];
        [self.backgroundImage addSubview:self.photoBtn];
        [self.backgroundImage addSubview:self.tipLabel];
        [self.backgroundImage addSubview:self.inputView];
        [self.backgroundImage addSubview:self.applyTypeLabel];
        [self.backgroundImage addSubview:self.coachBtn];
        [self.backgroundImage addSubview:self.companyBtn];
        [self.backgroundImage addSubview:self.uploadDriveCardBtn];
        [self.backgroundImage addSubview:self.uploadCoachCardBtn];
        [self.backgroundImage addSubview:self.nextStepBtn];
        self.backgroundImage.height = _nextStepBtn.bottom+20;
        self.contentSize = CGSizeMake(self.width, self.backgroundImage.height+10);
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
        [self addGestureRecognizer:tapGesture];
        [self registerForKeyboardNotifications];
    }
    return self;
}

#pragma mark - actions
- (void)tapAction
{
    [self.superview endEditing:YES];
}

- (void)selectRoleAction:(UIButton *)sender
{
    self.coachBtn.selected = (sender==self.coachBtn);
    self.companyBtn.selected = (sender==self.companyBtn);
    if (self.coachBtn.selected)
    {
        [self.uploadCoachCardBtn setImage:[UIImage imageNamed:@"教练证"] forState:UIControlStateNormal];
        [_uploadDriveCardBtn setImage:[UIImage imageNamed:@"身份证"] forState:UIControlStateNormal];
        self.registerInfo.carCardImg=nil;
        
        
    }
    else
    {
        [self.uploadCoachCardBtn setImage:[UIImage imageNamed:@"行驶证"] forState:UIControlStateNormal];
         [_uploadDriveCardBtn setImage:[UIImage imageNamed:@"驾驶证"] forState:UIControlStateNormal];
        self.registerInfo.coachCardImg=nil;
    }
    [self checkInputFinished];
}

- (void)nextStepAction:(UIButton *)sender
{
    if (![HDUtil checkName:self.nameField.text]) {
        [netEngine showErrorAlertWithMsg:@"姓名格式不正确"];
        return;
    }
    if (![HDUtil checkIdCardNo:self.identityCardField.text]) {
        [netEngine showErrorAlertWithMsg:@"身份证格式不正确"];
        return;
    }
//    if (![HDUtil checkIdCardNo:self.driveCardField.text]) {
//        [netEngine showErrorAlertWithMsg:@"准驾证格式不正确"];
//        return;
//    }
    self.registerInfo.name = self.nameField.text;
    self.registerInfo.identityCardId = self.identityCardField.text;
    self.registerInfo.driveCardId = self.driveCardField.text;
    self.registerInfo.coachCardId = self.coachCardField.text;
    if ([self.delegate respondsToSelector:@selector(nextStepAction:)]) {
        [self.delegate performSelector:@selector(nextStepAction:) withObject:nil];
    }
}

- (void)selectPhoto:(UIButton *)sender
{
    self.clickedPhotoBtn = sender;
    
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
        UIImagePickerController *imgPickerVC = [[UIImagePickerController alloc] init];
        imgPickerVC.view.backgroundColor = [UIColor whiteColor];
        [imgPickerVC setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
        [imgPickerVC.navigationBar setBarStyle:UIBarStyleBlack];
        imgPickerVC.delegate = (id)self;
        imgPickerVC.navigationBar.tintColor = [UIColor whiteColor];
        //显示Image Picker
        imgPickerVC.allowsEditing = YES;
        [rootNavigation presentViewController:imgPickerVC animated:YES completion:nil];
        
    }else {
        NSLog(@"Album is not available.");
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"无法打开相册！" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert show];
    }
}

- (void)checkInputFinished
{
    BOOL checkImaUpload = NO;
    if (self.coachBtn.selected)
    {
        checkImaUpload = self.registerInfo.driveCardImg&&self.registerInfo.coachCardImg;
    }
    else
    {
        checkImaUpload = self.registerInfo.driveCardImg&&self.registerInfo.carCardImg;
    }
    self.nextStepBtn.enabled = (self.nameField.text.length&&self.identityCardField.text.length&&self.driveCardField.text.length&&checkImaUpload);
}

- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasShown:)
                                                 name:UIKeyboardDidShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self
                                            selector:@selector(textBeginEditing:)
                                                name:UITextViewTextDidBeginEditingNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self
                                            selector:@selector(textBeginEditing:)
                                                name:UITextFieldTextDidBeginEditingNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self
                                            selector:@selector(checkInputFinished)
                                                name:UITextFieldTextDidChangeNotification object:nil];
    
}

- (void)textBeginEditing:(NSNotification*)aNotification
{
    UIView* sender=[aNotification object];
    CGRect rect=sender.frame;
    rect.origin.y+=rect.size.height;
    self.activePoint=[[sender superview] convertPoint:rect.origin toView:self];
    self.activePoint=[self convertPoint:self.activePoint toView:self];
}

- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    kbSize.height+=30;
    
    float hiddenH=self.frame.size.height-(self.frame.size.height-kbSize.height);
    
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0,hiddenH, 0.0);
    self.contentInset = contentInsets;
    self.scrollIndicatorInsets = contentInsets;
    float activeH=self.frame.size.height-self.activePoint.y;
    if(kbSize.height>activeH)
    {
        float dif=activeH-kbSize.height;
        CGPoint scrollPoint = CGPointMake(0.0,0-dif);
        [self setContentOffset:scrollPoint animated:YES];
    }
}

- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    [UIView animateWithDuration:0.3 animations:^{
        UIEdgeInsets contentInsets = UIEdgeInsetsZero;
        self.contentInset = contentInsets;
        self.scrollIndicatorInsets = contentInsets;
    }];
}

#pragma mark - UIImagePickerControllerDelegate  相册
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [rootNavigation dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    UIImage *image= [info objectForKey:@"UIImagePickerControllerEditedImage"];
    UIImage *theImage = [self imageWithImageSimple:image scaledToSize:CGSizeMake(200.0, 200.0)];
    [self.clickedPhotoBtn setImage:theImage forState:UIControlStateNormal];
    if (self.clickedPhotoBtn==self.photoBtn) {
        self.registerInfo.avatarImg=theImage;
    }
    if (self.clickedPhotoBtn==self.uploadDriveCardBtn)
    {
        self.registerInfo.driveCardImg=theImage;
    }
    if (self.clickedPhotoBtn==self.uploadCoachCardBtn)
    {
        if (self.coachBtn.selected)
        {
            self.registerInfo.coachCardImg=theImage;
        }
        else
        {
            self.registerInfo.carCardImg=theImage;
        }
    }
    [self checkInputFinished];
    [rootNavigation dismissViewControllerAnimated:YES completion:nil];
}

-(UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

#pragma mark - getters
- (UIImageView *)backgroundImage
{
    if (!_backgroundImage) {
        _backgroundImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, 5, APPFRAME.size.width-20, (APPFRAME.size.width-20)*900/600.0)];
        UIImage *image = [UIImage imageNamed:@"填写资料背景图"];
        image = [image stretchableImageWithLeftCapWidth:0 topCapHeight:_backgroundImage.height-10];
        _backgroundImage.image = image;
        _backgroundImage.layer.masksToBounds = YES;
        _backgroundImage.userInteractionEnabled = YES;
    }
    return _backgroundImage;
}

- (UIButton *)photoBtn
{
    if (!_photoBtn) {
        _photoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _photoBtn.frame = CGRectMake((self.backgroundImage.width-76)/2.0, APPFRAME.size.width/3.0-55, 76, 76);
        _photoBtn.layer.cornerRadius = 38;
        _photoBtn.clipsToBounds = YES;
        _photoBtn.layer.masksToBounds = YES;
        _photoBtn.layer.borderColor = [UIColor whiteColor].CGColor;
        _photoBtn.layer.borderWidth = 5;
        _photoBtn.contentMode = UIViewContentModeScaleAspectFit;
        [_photoBtn setImage:[UIImage imageNamed:@"添加照片"] forState:UIControlStateNormal];
        [_photoBtn addTarget:self action:@selector(selectPhoto:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _photoBtn;
}

- (UILabel *)tipLabel
{
    if (!_tipLabel) {
        _tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, self.photoBtn.bottom, self.backgroundImage.width-20, 13)];
        _tipLabel.textAlignment = NSTextAlignmentCenter;
        _tipLabel.textColor = kLightGrayColor;
        _tipLabel.text = @"上传一张免冠正面照";
        _tipLabel.font = [UIFont systemFontOfSize:13];
    }
    return _tipLabel;
}

- (UIView *)inputView
{
    if (!_inputView) {
        _inputView = [[UIView alloc] initWithFrame:CGRectMake(10, self.coachBtn.bottom+5, self.backgroundImage.width-20, 132)];
        _inputView.layer.borderColor = [UIColor colorWithRed:0.8824 green:0.8824 blue:0.8824 alpha:1].CGColor;
        _inputView.layer.borderWidth = 0.5;
        _inputView.layer.cornerRadius = 5;
        for (int i=0; i<2; i++) {
            UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(15, (i+1)*44, _inputView.width-30, 0.5)];
            line.image = [UIImage imageNamed:@"dot"];
            [_inputView addSubview:line];
        }
        [_inputView addSubview:self.nameField];
        [_inputView addSubview:self.identityCardField];
        [_inputView addSubview:self.driveCardField];
    }
    return _inputView;
}

- (HDTextField *)nameField
{
    if (!_nameField) {
        _nameField = [[HDTextField alloc] initWithFrame:CGRectMake(10, 0, self.backgroundImage.width-40, 44)icon:@"头像" title:nil];
        _nameField.placeholder = @"请输入您的真实姓名";
        _nameField.font = [UIFont systemFontOfSize:15];
    }
    return _nameField;
}

- (HDTextField *)identityCardField
{
    if (!_identityCardField) {
        _identityCardField = [[HDTextField alloc] initWithFrame:CGRectMake(10, self.nameField.bottom, self.nameField.width, 44)icon:@"验证码" title:nil];
        _identityCardField.placeholder = @"请填写您的身份证号码";
        _identityCardField.font = [UIFont systemFontOfSize:15];
    }
    return _identityCardField;
}

- (HDTextField *)driveCardField
{
    if (!_driveCardField) {
        _driveCardField = [[HDTextField alloc] initWithFrame:CGRectMake(10, self.identityCardField.bottom, self.nameField.width, 44)icon:@"验证码" title:nil];
        _driveCardField.placeholder = @"请输入驾驶证档案编号";
        _driveCardField.font = [UIFont systemFontOfSize:15];
    }
    return _driveCardField;
}

- (HDTextField *)coachCardField
{
    if (!_coachCardField) {
        _coachCardField = [[HDTextField alloc] initWithFrame:CGRectMake(10, self.driveCardField.bottom, self.nameField.width, 44)icon:@"验证码" title:nil];
        _coachCardField.placeholder = @"输入您的教练证号";
        _coachCardField.font = [UIFont systemFontOfSize:15];
    }
    return _coachCardField;
}

- (UILabel *)applyTypeLabel
{
    if (!_applyTypeLabel) {
        _applyTypeLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, APPFRAME.size.width/3.0+40, 60, 20)];
        _applyTypeLabel.textColor = [UIColor hexStringToColor:@"#888888"];
        _applyTypeLabel.text = @"申请类型";
        _applyTypeLabel.font = [UIFont systemFontOfSize:13];
    }
    return _applyTypeLabel;
}

- (GXButton *)coachBtn
{
    if (!_coachBtn) {
        _coachBtn = [GXButton buttonWithType:UIButtonTypeCustom];
        _coachBtn.frame = CGRectMake(self.backgroundImage.width/2.0-100, self.applyTypeLabel.bottom, 60, 30);
        _coachBtn.imageViewFrame = CGRectMake(0, 4, 22, 22);
        _coachBtn.titleLabelFrame = CGRectMake(30, 0, 30, 30);
        _coachBtn.relayout = YES;
        [_coachBtn setTitle:@"教练" forState:UIControlStateNormal];
        [_coachBtn setTitleColor:[UIColor hexStringToColor:@"#888888"] forState:UIControlStateNormal];
        _coachBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        [_coachBtn setImage:[UIImage imageNamed:@"同意_未选中"] forState:UIControlStateNormal];
        [_coachBtn setImage:[UIImage imageNamed:@"同意_选中"] forState:UIControlStateSelected];
        _coachBtn.selected = YES;
        [_coachBtn addTarget:self action:@selector(selectRoleAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _coachBtn;
}

- (GXButton *)companyBtn
{
    if (!_companyBtn) {
        _companyBtn = [GXButton buttonWithType:UIButtonTypeCustom];
        _companyBtn.frame = CGRectMake(self.backgroundImage.width/2.0+40, self.applyTypeLabel.bottom, 60, 30);
        _companyBtn.imageViewFrame = CGRectMake(0, 4, 22, 22);
        _companyBtn.titleLabelFrame = CGRectMake(30, 0, 30, 30);
        _companyBtn.relayout = YES;
        [_companyBtn setTitle:@"陪练" forState:UIControlStateNormal];
        [_companyBtn setTitleColor:[UIColor hexStringToColor:@"#888888"] forState:UIControlStateNormal];
        _companyBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        [_companyBtn setImage:[UIImage imageNamed:@"同意_未选中"] forState:UIControlStateNormal];
        [_companyBtn setImage:[UIImage imageNamed:@"同意_选中"] forState:UIControlStateSelected];
        _companyBtn.selected = NO;
        [_companyBtn addTarget:self action:@selector(selectRoleAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _companyBtn;
}

- (UIButton *)uploadDriveCardBtn
{
    if (!_uploadDriveCardBtn) {
        _uploadDriveCardBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _uploadDriveCardBtn.frame = CGRectMake(self.backgroundImage.width/2.0-135, self.inputView.bottom+20, 115, 75);
        [_uploadDriveCardBtn setImage:[UIImage imageNamed:@"身份证"] forState:UIControlStateNormal];
        [_uploadDriveCardBtn addTarget:self action:@selector(selectPhoto:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _uploadDriveCardBtn;
}

- (UIButton *)uploadCoachCardBtn
{
    if (!_uploadCoachCardBtn)
    {
        _uploadCoachCardBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _uploadCoachCardBtn.frame = CGRectMake(self.backgroundImage.width/2.0+20, self.inputView.bottom+20, 115, 75);
        [_uploadCoachCardBtn setImage:[UIImage imageNamed:@"教练证"] forState:UIControlStateNormal];
        [_uploadCoachCardBtn addTarget:self action:@selector(selectPhoto:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _uploadCoachCardBtn;
}

- (UIButton *)nextStepBtn
{
    if (!_nextStepBtn) {
        _nextStepBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _nextStepBtn.frame = CGRectMake(10, self.uploadDriveCardBtn.bottom+20, self.backgroundImage.width-20, 44);
        [_nextStepBtn setBackgroundImage:[UIImage imageNamed:@"登录"] forState:UIControlStateNormal];
        [_nextStepBtn setTitle:@"下一步" forState:UIControlStateNormal];
        _nextStepBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [_nextStepBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_nextStepBtn addTarget:self action:@selector(nextStepAction:) forControlEvents:UIControlEventTouchUpInside];
        _nextStepBtn.enabled = NO;
    }
    return _nextStepBtn;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
